package m202401.d14;

import java.util.LinkedList;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/14 18:21
 */
//637. 二叉树的层平均值
public class Q637 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new LinkedList<>();
        LinkedList<TreeNode> list = new LinkedList<>();
        LinkedList<TreeNode> line = new LinkedList<>();
        line.addLast(root);
        while (!list.isEmpty() || !line.isEmpty()) {
            if (list.isEmpty()) {
                result.add(line.stream().mapToLong(x -> x.val).sum() / (line.size() * 1.0));
                list = line;
                line = new LinkedList<>();
                continue;
            }
            TreeNode treeNode = list.removeFirst();
            if (treeNode.left != null) {
                line.addLast(treeNode.left);
            }
            if (treeNode.right != null) {
                line.addLast(treeNode.right);
            }
        }
        return result;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
